//
//  MyVipViewController.m
//  markmap
//
//  Created by 甘世清 on 2024/6/16.
//

#import "MyVipViewController.h"
#import <RMStore/RMStore.h>
#import "VipCollectionViewCell.h"
#import "MiDouModel.h"
#import "VipTableViewCell.h"
@interface MyVipViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UITableViewDelegate,UITableViewDataSource>
@property (nonatomic , strong) MiDouModel * seletedModel;
@property (nonatomic , strong) HeaderView * avatarImage;
@property (nonatomic , strong) UILabel * nameLabel;
@property (nonatomic , strong) UILabel * zhuangtai;
@property (nonatomic , strong) HeaderView * addButton;
@end

@implementation MyVipViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.blackColor;
    [self zx_setRightBtnWithText:SQNSLocalString(@"恢复购买") clickedBlock:^(ZXNavItemBtn * _Nonnull btn) {
        [YJProgressHUD SQ_showMsgWithoutView:@""];
       [[RMStore defaultStore] restoreTransactionsOnSuccess:^(NSArray *transactions) {
             [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"没有购买可以恢复")];
        } failure:^(NSError *error) {
            [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"暂无数据")];
        }];
    }];
    self.zx_navBar.zx_rightBtn.zx_fixWidth = 60;
     self.zx_navBar.zx_rightBtn.zx_fixImageSize = CGSizeMake(0, 0);
    self.zx_navBar.zx_rightBtn.titleLabel.font = FONT_REGULAR(14);
    self.zx_navBar.zx_rightBtn.zx_tintColor = SQColor(@"#C7ABF7");
}

- (void)SQ_UIViewForSelfView{
    
    UIImageView * topImage = [[UIImageView alloc]init];
    topImage.image = SQGetImage(@"VIP 会员");
    [self.view addSubview:topImage];
    [topImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(112);
        make.height.mas_equalTo(55);
        make.top.equalTo(self.zx_navBar.mas_bottom);
        make.left.equalTo(self.view).offset(28);
    }];
    UIImageView * bgimage = [[UIImageView alloc]init];
    bgimage.image = SQGetImage(@"编组 4");
    [self.view addSubview:bgimage];
    [bgimage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(SCREEN_WIDETH-32);
        make.centerX.equalTo(self.view);
        make.height.mas_equalTo(132);
        make.top.equalTo(self.zx_navBar.mas_bottom).offset(35);
    }];
    [bgimage addSubview:self.avatarImage];
    [bgimage addSubview:self.nameLabel];
    [self.avatarImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(64);
        make.left.equalTo(bgimage).offset(16);
        make.bottom.equalTo(bgimage.mas_bottom).offset(-16);
    }];
    [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.avatarImage).offset(8);
        make.left.equalTo(self.avatarImage.mas_right).offset(10);
    }];
    [bgimage addSubview:self.zhuangtai];
    [self.zhuangtai mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.avatarImage).offset(34);
        make.left.equalTo(self.avatarImage.mas_right).offset(10);
        make.width.mas_equalTo(56);
        make.height.mas_equalTo(24);
    }];
    if ([UserModel share].isVip) {
        self.zhuangtai.text = SQNSLocalString(@"已开通");
    }
    
    UIImageView * bgimage2 = [[UIImageView alloc]init];
    bgimage2.image = SQGetImage(@"Vip矩形");
    bgimage2.contentMode = UIViewContentModeScaleAspectFill;
    bgimage2.clipsToBounds = YES;
    [self.view addSubview:bgimage2];
    [bgimage2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(bgimage.mas_bottom);
    }];
    
    [self.collectionView registerClass:[VipCollectionViewCell class] forCellWithReuseIdentifier:@"VipCollectionViewCell"];
    self.collectionView.alwaysBounceVertical = NO;
    UICollectionViewFlowLayout* flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.collectionView.collectionViewLayout = flowLayout;
    [self.view addSubview:self.collectionView];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(bgimage2).offset(16);
        make.right.equalTo(bgimage2.mas_right).offset(-16);
            make.top.equalTo(bgimage2).offset(0);
            make.height.mas_equalTo(124);
    }];
    
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(bgimage2);
        make.top.equalTo(self.collectionView.mas_bottom);
        make.bottom.equalTo(self.view.mas_bottom).offset(-FootHeight-160);
    }];
    [self.view addSubview:self.addButton];
    [self.addButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.width.mas_equalTo(264);
            make.height.mas_equalTo(48);
            make.top.equalTo(self.tableView.mas_bottom).offset(20);
    }];
    
    YYLabel * label3 = [[YYLabel alloc]initWithFrame:CGRectMake(18, SCREEN_HEIGHT- FootHeight-50, SCREEN_WIDETH-38, 50)];
    label3.textVerticalAlignment = YYTextVerticalAlignmentCenter;
    label3.textAlignment = NSTextAlignmentCenter;
    label3.numberOfLines = 0;
    [self.view addSubview:label3];
    NSDictionary *attributes = @{NSFontAttributeName:FONT_MEDIUM(12) , NSForegroundColorAttributeName: SQColor(@"#DBDBDB")};
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:SQNSLocalString(@" 点击阅读《自动续费与增值服务协议》《隐私协议》《用户协议》,自动续费可随时在账户设置中取消订阅. 服务到期时,将从您的付费渠道自动扣费并续期vip权益.") attributes:attributes];
    WS(weakSelf);
    //设置高亮色和点击事件
    [text yy_setTextHighlightRange:[[text string] rangeOfString:SQNSLocalString(@"《自动续费与增值服务协议》")] color:SQColor(@"#F835E5") backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        CommonWebVcView *vc= [[CommonWebVcView alloc]init];
        vc.urlStr =  ZZFWXY;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    NSRange range1=[[text string]rangeOfString:SQNSLocalString(@"《自动续费与增值服务协议》")];
    YYTextDecoration* deco=[YYTextDecoration decorationWithStyle:(YYTextLineStyleSingle) width:[NSNumber numberWithInt:0] color:[UIColor whiteColor]];
    [text yy_setTextUnderline:deco range:range1];
    
    //设置高亮色和点击事件
    [text yy_setTextHighlightRange:[[text string] rangeOfString:SQNSLocalString(@"《隐私协议》")] color:SQColor(@"#F835E5") backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        CommonWebVcView *vc= [[CommonWebVcView alloc]init];
        vc.urlStr =  YSTK;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    NSRange range2=[[text string]rangeOfString:SQNSLocalString(@"《隐私协议》") ];
    YYTextDecoration* deco2=[YYTextDecoration decorationWithStyle:(YYTextLineStyleSingle) width:[NSNumber numberWithInt:0] color:[UIColor whiteColor]];
    [text yy_setTextUnderline:deco2 range:range2];
    
    //设置高亮色和点击事件
    [text yy_setTextHighlightRange:[[text string] rangeOfString:SQNSLocalString(@"《用户协议》")] color:SQColor(@"#F835E5") backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        CommonWebVcView *vc= [[CommonWebVcView alloc]init];
        vc.urlStr =  YHXY;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    NSRange range3=[[text string]rangeOfString:SQNSLocalString(@"《用户协议》")];
    YYTextDecoration* deco3 =[YYTextDecoration decorationWithStyle:(YYTextLineStyleSingle) width:[NSNumber numberWithInt:0] color:[UIColor whiteColor]];
    [text yy_setTextUnderline:deco3 range:range3];
    
    label3.attributedText = text;
    
    [self SQ_header];
}
-(void)SQ_header{
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [HttpTool post:Url20 paramDic:dic successBlock:^(BaseModel * _Nonnull httpModel) {
        [self.jsonArray removeAllObjects];
        NSArray * array = [MiDouModel mj_objectArrayWithKeyValuesArray:httpModel.data];
        [self.jsonArray addObjectsFromArray:array];
        [self.tableView reloadData];
        if (array.count > 0) {
            self.seletedModel = array.firstObject;
            self.seletedModel.isseleted = YES;
            [self SQ_RMStore];
            [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionMiddle];
        }
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        [YJProgressHUD showMsgWithoutView:httpModel.data];
    }];
}
-(void)SQ_RMStore{
 
    NSMutableArray * array = [[NSMutableArray alloc]init];
    [self.jsonArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        MiDouModel * model = (MiDouModel*)obj;
        if ([model.appleId isNotEmpty]) {
            [array addObject:model.appleId];
        }
    }];
     [[RMStore defaultStore] requestProducts:[NSSet setWithArray:array] success:^(NSArray *products, NSArray *invalidProductIdentifiers) {
        if([products count] == 0){
            DTLog(@"--------------没有商品------------------");
            return;
        }
        DTLog(@"内购商品列表------%@",products);
    } failure:^(NSError *error) {
        DTLog(@"--------------请求商品失败--------------%@----",error);
    }];
}

-(void)SQ_addMidou{
   
    [YJProgressHUD SQ_showMsgWithoutView:@""];
    WS(weakSelf);
     [[RMStore defaultStore] addPayment:self.seletedModel.appleId success:^(SKPaymentTransaction *transaction) {
            [weakSelf checkIAPResultWithtransactionReceiptblock];
        } failure:^(SKPaymentTransaction *transaction, NSError *error) {
            [YJProgressHUD showMsgWithoutView: SQNSLocalString(@"交易失败")];
    }];
    
}
- (void)checkIAPResultWithtransactionReceiptblock
{
    [YJProgressHUD SQ_showMsgWithoutView:@""];
    NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
        if (receiptURL) {
            NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];
            NSString *encodeStr = [receiptData base64EncodedStringWithOptions: NSDataBase64EncodingEndLineWithLineFeed];
             NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
            [dic setObject:encodeStr forKey:@"certificate"];
             [YJProgressHUD SQ_showMsgWithoutView:@""];
            [HttpTool post:Url56 paramDic:dic successBlock:^(BaseModel * _Nullable httpModel) {
                
                for (SKPaymentTransaction *aTransaction in [[SKPaymentQueue defaultQueue] transactions]) {
                    [[SKPaymentQueue defaultQueue]finishTransaction:aTransaction];
                }
                [self SQ_goumaichenggong];
            } andFailBloc:^(BaseModel * _Nullable httpModel, NSError * _Nullable error) {
                [YJProgressHUD showMsgWithoutView:httpModel.message];
            }];
        }else{
            [YJProgressHUD hide];
           
        }
}
-(void)SQ_goumaichenggong{
    UserModel * model = [UserModel share];
    model.isVip = YES;
    [UserModel updateLocalUserModel:model];
    [self SQ_popViewVC];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
     return self.jsonArray.count;
}
 
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    VipTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"VipTableViewCell"];
    if (!cell) {
        cell = [[VipTableViewCell alloc] initWithStyle:(UITableViewCellStyleValue1) reuseIdentifier:@"VipTableViewCell"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = [self.jsonArray objectAtIndex:indexPath.item];
    return cell;
}
 

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    MiDouModel * model = [self.jsonArray objectAtIndex:indexPath.item];
    if ([model.name isEqualToString:self.seletedModel.name]) {
        return 102;
    }
    return  92;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    self.seletedModel.isseleted = NO;
    self.seletedModel = [self.jsonArray objectAtIndex:indexPath.item];
    self.seletedModel.isseleted = YES;
    [self.tableView reloadData];
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
}

#pragma mark UICollectionViewDelegate,UICollectionViewDataSource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 4;
}

-(UICollectionViewCell *)collectionView:(UICollectionView*)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath{
    VipCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"VipCollectionViewCell" forIndexPath:indexPath];
    if (indexPath.item==0) {
        cell.name = @"VIP 图标";
    } else if (indexPath.item==1){
        cell.name = @"访客";
    } else if (indexPath.item==2){
        cell.name = @"打招呼";
    } else if (indexPath.item==3){
        cell.name = @"人气值";
    }  
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat w = 17+14+83;
    return CGSizeMake(w, 120);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];

}


- (HeaderView *)avatarImage{
    if (!_avatarImage) {
        _avatarImage = [[HeaderView alloc]init];
        _avatarImage.headerImage.contentMode = UIViewContentModeScaleAspectFill;
        _avatarImage.clipsToBounds = YES;
        _avatarImage.layer.cornerRadius = 32;
        _avatarImage.layer.borderColor = UIColor.whiteColor.CGColor;
        _avatarImage.layer.borderWidth = 1;
        [_avatarImage.headerImage sd_setImageWithURL:SQURLImage([UserModel share].portrait) placeholderImage:SQGetImage(@"zanwutouxiang")];
    }
    return _avatarImage;
}
- (UILabel *)nameLabel{
    if (!_nameLabel) {
        _nameLabel = [[UILabel alloc]init];
        _nameLabel.font = FONT_SEMIBOLD(18);
        _nameLabel.textColor = UIColor.whiteColor;
        _nameLabel.text = [UserModel share].name;
    }
    return _nameLabel;
}

- (UILabel *)zhuangtai{
    if (!_zhuangtai) {
        _zhuangtai = [[UILabel alloc]init];
        _zhuangtai.textColor =SQColorF4F4F4;
        _zhuangtai.font = FONT_REGULAR(13);
        _zhuangtai.text = SQNSLocalString(@"未开通");
        _zhuangtai.backgroundColor = UIColor.blackColor;
        _zhuangtai.layer.cornerRadius = 12;
        _zhuangtai.textAlignment = NSTextAlignmentCenter;
        _zhuangtai.layer.masksToBounds = YES;
    }
    return _zhuangtai;
}
- (HeaderView *)addButton{
    if (!_addButton) {
        _addButton = [[HeaderView alloc]init];
        _addButton.colorString = @"#333333";
        [_addButton.btn addTarget:self action:@selector(SQ_addMidou) forControlEvents:UIControlEventTouchUpInside];
        _addButton.layer.cornerRadius = 24;
        _addButton.layer.masksToBounds = YES;
        _addButton.backgroundColor = UIColor.whiteColor;
        _addButton.text = SQNSLocalString(@"VIP获取");
        _addButton.font = FONT_MEDIUM(18);
    }
    return _addButton;
}
@end
